package com.shujia.spark.stream

import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Duration, Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}

object Demo1WordCount {
  def main(args: Array[String]): Unit = {
    val conf: SparkConf = new SparkConf()
      .setMaster("local[2]")
      .setAppName("wc")

    val sc = new SparkContext(conf)

    /**
      * 创建spark streaming环境
      *
      */

    val ssc = new StreamingContext(sc, Durations.seconds(5))


    /**
      * 启动socket
      * yum install nc
      * nc -lk 8888
      *
      */

    //1、读取数据
    val lineDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)


    val wordDS: DStream[String] = lineDS.flatMap(line => line.split(","))

    val kvDS: DStream[(String, Int)] = wordDS.map((_, 1))

    val countDS: DStream[(String, Int)] = kvDS.reduceByKey(_ + _)

    //打印出来
    countDS.print()




    //启动spark streaming程序
    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
